package main

import "sync"

type JobManager struct {
	jobMutex   sync.RWMutex
	activeJobs map[string]DeployJob
}

func (jm *JobManager) sync(jobs []DeployJob) {
	jm.jobMutex.Lock()
	defer jm.jobMutex.Unlock()
	// 增量更新
	dict := make(map[string]DeployJob, 0)
	for _, j := range jobs {
		if v, ok := jm.activeJobs[j.GetName()]; !ok {
			jm.activeJobs[j.GetName()] = v
			v.Start(jm)
		}
		dict[j.GetName()] = j
	}
	for k, v := range jm.activeJobs {
		if _, ok := dict[k]; !ok {
			v.Stop(jm)
		}
	}
}

type DeployJob interface {
	GetName() string
	Start(jm *JobManager)
	Stop(jm *JobManager)
}

type K8s struct {
	name string
}

func (k K8s) GetName() string {
	return k.name
}

func (k K8s) Start(jm *JobManager) {
	jm.jobMutex.Lock()
	defer jm.jobMutex.Unlock()
	jm.activeJobs[k.name] = k
}

func (k K8s) Stop(jm *JobManager) {
	jm.jobMutex.Lock()
	defer jm.jobMutex.Unlock()
	delete(jm.activeJobs, k.name)
}

type Host struct {
	name string
}

func (h Host) GetName() string {
	return h.name
}

func (h Host) Start(jm *JobManager) {
	jm.jobMutex.Lock()
	defer jm.jobMutex.Unlock()
	jm.activeJobs[h.name] = h
}

func (h Host) Stop(jm *JobManager) {
	jm.jobMutex.Lock()
	defer jm.jobMutex.Unlock()
	delete(jm.activeJobs, h.name)
}
